package com.yanqu.road.dao.impl.player;

import com.yanqu.road.dao.db.DbNameStrategy;
import com.yanqu.road.dao.db.DbParameter;
import com.yanqu.road.dao.impl.TempDataObjectDao;
import com.yanqu.road.entity.orewar.UserOreRefuge;
import com.yanqu.road.utils.string.StringUtils;

import java.sql.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class UserOreRefugeDaoImpl extends TempDataObjectDao<UserOreRefuge> {

    public boolean isNeedRecallRefugeUser(int activityId,long userId,long timestampSecNeed) {
        ResultSet rs = null;
        CallableStatement call = null;
        String sql = "SELECT * FROM t_u_activity_orewar_refuge WHERE patronsIdList!='' AND activityId=? AND joinTime <= ? AND userId = ?" +
                " GROUP BY userId";
        try {
            getDb().setConnName(DbNameStrategy.getUserDb());
            call = getDb().getConnection().prepareCall(sql);
            int i = 1;
            call.setLong(i++, activityId);
            call.setLong(i++, timestampSecNeed);
            call.setLong(i++, userId);
            rs = call.executeQuery();
            while (rs.next()) {
                return true;
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            getDb().closeConnection(call, rs);
        }
        return false;
    }

    public List<Long> getNeedRecallRefugeUserList(int activityId,long timestampSecNeed) {
        List<Long> dataMap = new ArrayList<>();
        ResultSet rs = null;
        CallableStatement call = null;
        String sql = "SELECT * FROM t_u_activity_orewar_refuge WHERE patronsIdList!='' AND activityId=? AND joinTime <= ?" +
                " GROUP BY userId";
        try {
            getDb().setConnName(DbNameStrategy.getUserDb());
            call = getDb().getConnection().prepareCall(sql);
            int i = 1;
            call.setLong(i++, activityId);
            call.setLong(i++, timestampSecNeed);
            rs = call.executeQuery();
            while (rs.next()) {
                dataMap.add(rs.getLong("userId"));
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            getDb().closeConnection(call, rs);
        }
        return dataMap;
    }

    public Map<Integer, UserOreRefuge> getUserOreRefugeMap(long userId,int activityId) {
        Map<Integer, UserOreRefuge> dataMap = new ConcurrentHashMap<>();
        ResultSet rs = null;
        CallableStatement call = null;
        String sql = "select * from t_u_activity_orewar_refuge where userId=? AND activityId=?";
        try {
            getDb().setConnName(DbNameStrategy.getUserDb());
            call = getDb().getConnection().prepareCall(sql);
            int i = 1;
            call.setLong(i++, userId);
            call.setLong(i++, activityId);
            rs = call.executeQuery();
            while (rs.next()) {
                UserOreRefuge data = parse(rs);
                dataMap.put(data.getPitId(), data);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            getDb().closeConnection(call, rs);
        }
        return dataMap;
    }

    public void updateUserOreRefugeList(List<UserOreRefuge> userOreRefugeList) {
        String sql = "UPDATE t_u_activity_orewar_refuge SET patronsIdList=?,joinTime=?,lastGetRewardTime=? WHERE activityId=? and pitId=? and userId=?";
        try {
            getDb().setConnName(DbNameStrategy.getUserDb());
            List<Map<Integer, DbParameter>> mapList = new ArrayList<>();
            for (UserOreRefuge userOreRefuge : userOreRefugeList){
                Map<Integer, DbParameter> para = new HashMap<>();
                int i = 1;
                para.put(i++, new DbParameter(Types.VARCHAR, StringUtils.listToString(userOreRefuge.getPatronsIdList(),',')));
                para.put(i++, new DbParameter(Types.BIGINT, userOreRefuge.getJoinTime()));
                para.put(i++, new DbParameter(Types.BIGINT, userOreRefuge.getLastGetRewardTime()));

                para.put(i++, new DbParameter(Types.INTEGER, userOreRefuge.getActivityId()));
                para.put(i++, new DbParameter(Types.INTEGER, userOreRefuge.getPitId()));
                para.put(i++, new DbParameter(Types.BIGINT, userOreRefuge.getUserId()));
                mapList.add(para);
            }
            if (mapList.size() > 0) {
                getDb().executeBatchQuery(sql, mapList);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {

        }
    }

    @Override
    protected boolean addData(UserOreRefuge data) {
        PreparedStatement call = null;
        String sql = "INSERT INTO t_u_activity_orewar_refuge(activityId,pitId,userId,patronsIdList,joinTime,lastGetRewardTime) VALUES (?,?,?,?,?,?)";
        try {
            getDb().setConnName(DbNameStrategy.getUserDb());
            call = getDb().getConnection().prepareStatement(sql);
            int i = 1;
            call.setInt(i++, data.getActivityId());
            call.setInt(i++, data.getPitId());
            call.setLong(i++, data.getUserId());
            call.setString(i++, StringUtils.listToString(data.getPatronsIdList(),','));
            call.setLong(i++, data.getJoinTime());
            call.setLong(i++, data.getLastGetRewardTime());
            return call.executeUpdate() > 0;
        } catch (Exception e) {
            logger.error(Thread.currentThread().getStackTrace()[1].getMethodName() + ":", e);
        } finally {
            getDb().closeConnection(call, null);
        }
        return false;
    }

    @Override
    protected boolean updateData(UserOreRefuge data) {
        PreparedStatement call = null;
        String sql = "UPDATE t_u_activity_orewar_refuge SET patronsIdList=?,joinTime=?,lastGetRewardTime=? where activityId=? and pitId=? and userId=?";
        try {
            getDb().setConnName(DbNameStrategy.getUserDb());
            call = getDb().getConnection().prepareStatement(sql);
            int i = 1;
            call.setString(i++, StringUtils.listToString(data.getPatronsIdList(),','));
            call.setLong(i++, data.getJoinTime());
            call.setLong(i++, data.getLastGetRewardTime());
            call.setInt(i++, data.getActivityId());
            call.setInt(i++, data.getPitId());
            call.setLong(i++, data.getUserId());
            return call.executeUpdate() > 0;
        } catch (Exception e) {
            logger.error(Thread.currentThread().getStackTrace()[1].getMethodName() + ":", e);
        } finally {
            getDb().closeConnection(call, null);
        }
        return false;
    }

    @Override
    protected UserOreRefuge parseData(ResultSet rs) throws SQLException {
        UserOreRefuge data = new UserOreRefuge();
        data.setActivityId(rs.getInt("activityId"));
        data.setPitId(rs.getInt("pitId"));
        data.setUserId(rs.getLong("userId"));
        data.setJoinTime(rs.getLong("joinTime"));
        data.setLastGetRewardTime(rs.getLong("lastGetRewardTime"));
        data.setPatronsIdList(StringUtils.stringToIntegerListNoZero(rs.getString("patronsIdList"), ","));
        return data;
    }
}
